/**
 * 只允许输入数字指令
 */

import {
    getInputElement,
    replaceNumber,
    toRealNumber,
    getCompositionEvent,
} from './utils';

export default {
    beforeMount: async (el, binding) => {
        const IS_SUPPORT = await getCompositionEvent();
        const data = binding?.instance?.$data;
        let obj = null;
        let key = '';

        if (binding.value) {
            const arr = binding.value.split('.');
            arr.reduce((pre, cur, index) => {
                if (index === arr.length - 1) {
                    obj = pre;
                    key = cur;
                }

                return pre[cur];
            }, data);
        }

        el = getInputElement(el);

        el.onlyNumberHandler = () => {
            // 如果未开启输入
            if (el.lockedInput) {
                return;
            }

            const float = el.getAttribute('data-float') === 'false';
            const zero = el.getAttribute('data-zero') === 'false';
            const maxLength = el.getAttribute('maxlength');
            // 将全角数字转换为数字
            let res = toRealNumber(el.value);

            // 根据maxLength控制字符长度
            // 修改原生maxLength属性无法控制日文输入法输入长度问题
            if (maxLength && res.length > maxLength) {
                res = res.slice(0, maxLength);
            }

            const result = res.trim().split('.');

            let value;

            if (result.length === 1 || float) {
                value = replaceNumber(result[0]);
            } else if (result.length > 1) {
                value = `${replaceNumber(result[0])}.${replaceNumber(result[1])}`;
            }

            // 允许输入小数 校验小数规则
            if (!float && /(^0{2,})|(^\.)|(^0[^.]+)/.test(value)) {
                value = value.length > 1 ? value.slice(-1) : '';
            }

            // 如果不允许输入0
            if (zero && float && Number(value) === 0) {
                value = '';
            }

            // 更新原文本框显示值
            el.value = value;

            // 如果有 v-model 则更新数据
            if (binding.value) {
                obj[key] = el.value;
            }
        };

        // 当不允许输入零时
        el.checkNumberHandler = () => {
            const zero = el.getAttribute('data-zero') === 'false';
            // 如果不允许输入0  将 0 or 0. 清空
            if (zero && ((Number(el.value) === 0 && el.value !== '') || el.value === '0.')) {
                // 更新原文本框显示值
                el.value = '';

                // 如果有 v-model 则更新数据
                if (binding.value) {
                    obj[key] = el.value;
                }

                el.focus();
            }
        };

        if (IS_SUPPORT) {
            el.compositionstartHandler = () => {
                el.lockedInput = true;
            };
            el.compositionendHandler = () => {
                el.lockedInput = false;
                el.onlyNumberHandler();
            };

            el.addEventListener('compositionstart', el.compositionstartHandler);
            el.addEventListener('compositionend', el.compositionendHandler);
            el.addEventListener('input', el.onlyNumberHandler);
        } else {
            el.addEventListener('input', el.onlyNumberHandler);
        }
    },
    mounted: (el) => {
        el = getInputElement(el);

        // 先执行下，以防默认有值
        if (typeof el.onlyNumberHandler === 'function') {
            el.onlyNumberHandler();
        }
    },
    unmounted: (el) => {
        el = getInputElement(el);

        [
            ['compositionstart', 'compositionstartHandler'],
            ['compositionend', 'compositionendHandler'],
            ['input', 'onlyNumberHandler'],
            ['blur', 'checkNumberHandler'],
        ].forEach(([event, key]) => {
            if (el[key]) {
                el.removeEventListener(event, el[key]);
                delete el[key];
            }
        });
    },
};
